package cpu.footprint.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import cpu.footprint.R;
import cpu.footprint.adapter.CommonAdapter;
import cpu.footprint.adapter.ViewHolder;
import cpu.footprint.api.MyApplication;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.SerachInfo;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.ViewUtil;

/**
 * Created by Administrator on 2017/3/28.
 */
@ContentView(R.layout.activity_mapserach)
public class MapSerachActivity extends BaseActivity {
    @ViewInject(R.id.title_content)
    private TextView title_content;//title内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//title功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//title功能
    @ViewInject(R.id.edit_serach)
    private EditText edit_serach;//搜索
    @ViewInject(R.id.listview_serachCity)
    private ListView listview_serachCity;
    private Dialog mDialog;
    private User user=new User();
    private MyApplication myApplication;
    private Context mContext;
    private SuggestionSearch mSuggestionSearch = null;
    private List<SerachInfo> mSerachInfo = new ArrayList<SerachInfo>();
    private CommonAdapter<SerachInfo> sugadapter = null;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mDialog != null) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
            }
            switch (msg.what) {

                case ResultMessage.FAILED:
                    CreateDialogUtil.ToastShow(mContext, "连接失败");
                    break;
                case ResultMessage.TIMEOUT:
                    CreateDialogUtil.ToastShow(mContext, "连接超时");
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(this.getApplicationContext());
        initView();
        myApplication= (MyApplication) this.getApplication();
        mContext=MapSerachActivity.this;
        if(myApplication.isLogin()){
            user=myApplication.getUser();
        }else{
            Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.putExtra("IsLogin", false);
            startActivity(intent);
            overridePendingTransition(0,R.anim.fade);
            finish();
            return;
        }
    }

    /**
     * 初始化View
     */
    private void initView() {
        //ViewUtil.setSteep(this);//沉浸式菜单
        title_content.setText("搜索地点");
        title_menu_image.setVisibility(View.GONE);
        title_menu_text.setVisibility(View.GONE);
        mDialog= CreateDialogUtil.CreateDialog(MapSerachActivity.this,"请稍后...",mHandler);
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(suggestionlistener);
        listview_serachCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView= (TextView) view.findViewById(R.id.text_serachCity);
                TextView textView_City= (TextView) view.findViewById(R.id.text_city);
                TextView text_Latitude= (TextView) view.findViewById(R.id.text_Latitude);
                TextView text_Longitude= (TextView) view.findViewById(R.id.text_Longitude);
                String activitySite=textView.getText().toString().trim();
                String activityCity=textView_City.getText().toString().trim();
                String latitudeStr=text_Latitude.getText().toString().trim();
                String longitudeStr=text_Longitude.getText().toString().trim();
                double latitude=0.0;
                double longitude=0.0;
                if(!latitudeStr.isEmpty()&&latitudeStr!=null){
                    latitude=Double.parseDouble(latitudeStr);
                }
                if(!longitudeStr.isEmpty()&&longitudeStr!=null){
                    longitude=Double.parseDouble(longitudeStr);
                }
               // LatLng location=new LatLng(latitude,longitude);
                edit_serach.setText(activitySite);
                Intent intent=new Intent();
                intent.putExtra("activitySite",activitySite);
                intent.putExtra("activityCity",activityCity);
                intent.putExtra("latitude",latitude);
                intent.putExtra("longitude",longitude);
                setResult(1,intent);
                MapSerachActivity.this.finish();
                overridePendingTransition(0,R.anim.fade);
            }
        });
        edit_serach.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() <= 0) {
                    mSerachInfo.clear();
                    if (sugadapter != null)
                        sugadapter.notifyDataSetChanged();
                    return;
                }
                /**
                 * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                 */
//                clear_history.setVisibility(View.GONE);
//                serach_list.setVisibility(View.GONE);
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(s.toString()).city("重庆市"));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        initAdapter(mSerachInfo);
    }
    @Event(value = {R.id.title_back})
    private void OnClick(View v){
        switch (v.getId()) {
            case R.id.title_back: {
                this.finish();
                overridePendingTransition(0,R.anim.fade);
            }
            break;
            default:break;
        }
    }
    private void initAdapter(List<SerachInfo> mSerachInfo) {
        sugadapter = new CommonAdapter<SerachInfo>(this, mSerachInfo,
                R.layout.serach_item) {
            @Override
            public void convert(ViewHolder helper, SerachInfo item, int position) {
                LatLng p2 = new LatLng(item.getmLatitude(),
                        item.getmLongitude());
//                TextView text_Latitude= (TextView) view.findViewById(R.id.text_Latitude);
//                TextView text_Longitude= (TextView) view.findViewById(R.id.text_Longitude);
                helper.setText(R.id.text_Latitude,""+item.getmLatitude());
                helper.setText(R.id.text_city,item.getmAddress());
                helper.setText(R.id.text_Longitude,""+item.getmLongitude());
                helper.setText(R.id.text_serachCity,item.getKey());
            }

        };
        listview_serachCity.setAdapter(sugadapter);
        sugadapter.notifyDataSetChanged();
    }
    /**
     * 搜索监听
     */
    OnGetSuggestionResultListener suggestionlistener = new OnGetSuggestionResultListener() {
        public void onGetSuggestionResult(SuggestionResult res) {
            mSerachInfo.clear();
            if (res == null || res.getAllSuggestions() == null) {
                return;
                // 未找到相关结果
            }
            for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
                if (info.key != null && (info.pt != null)) {
                    SerachInfo item = new SerachInfo();
                    item.setmAddress(info.city);
                    item.setKey(info.key);
                    item.setmLatitude(info.pt.latitude);
                    item.setmLongitude(info.pt.longitude);
                    mSerachInfo.add(item);
                }
            }
            if (mSerachInfo != null) {
                initAdapter(mSerachInfo);
            }
            sugadapter.notifyDataSetChanged();
        }

    };
    /**
     * 重写后退函数
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            MapSerachActivity.this.finish();
            overridePendingTransition(0,R.anim.fade);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }
}
